package com.authine.cloudpivot.ext.applicationservice;

import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.applicationservice.base.ApplicationBaseService;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.dto.OrderCustomerGoodsDto;
import com.authine.cloudpivot.ext.enums.order.OrderCustomerStatusEnum;
import com.authine.cloudpivot.ext.enums.order.OrderGoodsStatusEnum;
import com.authine.cloudpivot.ext.enums.report.ReportType;
import com.authine.cloudpivot.ext.service.OrderService;
import com.authine.cloudpivot.ext.service.impl.OrderServiceImpl;
import com.authine.cloudpivot.ext.utils.StringUtils;
import com.authine.cloudpivot.ext.utils.boQuery.BoQueryUtils;
import com.authine.cloudpivot.ext.utils.system.ReportUtils;
import com.authine.cloudpivot.ext.vo.TempOrderReceiptVo;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.authine.mvp.app.launcher.dto.bo.response.BOList;
import com.authine.mvp.app.launcher.rpc.SaveOrUpdateBO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.*;
import java.util.stream.Collectors;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

/**
 * @ClassName CustomerDeliveryService
 * @Description: 客户收货自定义服务
 * @Author cjj
 * @Date 2021/4/20
 * @Version V1.0
 **/
@Path("CustomerDeliveryService")
@Slf4j
public class CustomerDeliveryService extends ApplicationBaseService {
    private OrderService orderService = new OrderServiceImpl();
    private NamedParameterJdbcTemplate jdbcTemplate = ApplicationContextUtils.getBean(NamedParameterJdbcTemplate.class);

    /**
     * 待收货listBo
     *
     * @param dto
     * @return
     */
    @Path("customerDeliveryList")
    @POST
    @Operation(summary = "客户收货-待收货-待收货列表分页查询", tags = CUSTOM_SERVICE)
    public SingleResponse<BOList> customerDeliveryList(@Parameter OrderCustomerGoodsDto dto) {
        if (StringUtils.isNotBlank(dto.getOrderCustomerGoodsStatus()) && (dto.getOrderCustomerGoodsStatus().equals(OrderGoodsStatusEnum.DoneDelivery.name()) ||
                dto.getOrderCustomerGoodsStatus().equals(OrderGoodsStatusEnum.UpcomingDelivery.name()))) {
            dto.setOrderCustomerGoodsStatus(dto.getOrderCustomerGoodsStatus());
        } else {
            dto.setOrderCustomerGoodsStatus(OrderGoodsStatusEnum.DoneDelivery.name() + ";" + OrderGoodsStatusEnum.UpcomingDelivery.name());
        }
        return deliveryList(dto);
    }

    /**
     * 分批收货
     *
     * @param dto
     * @return
     */
    @Path("customerPartReceipt")
    @POST
    @Operation(summary = "客户收货-待收货-收货-分批收货", tags = CUSTOM_SERVICE, description = "id、quantity必填")
    public SingleResponse<Boolean> customerPartReceipt(@Parameter OrderCustomerGoodsDto dto) {
        log.info("------------------------客户收货-待收货-收货 customerReceipt Param：{}------------------------", JSONObject.toJSONString(dto));
        if (StringUtils.isBlank(dto.getId())) {
            return SingleResponse.buildFailure("-1", "客户订单商品ID必填");
        }
        if (null == dto.getQuantity()) {
            return SingleResponse.buildFailure("-1", "数量必填");
        }
        Boolean result = orderService.goodsReceipt(dto.getId(), dto.getQuantity());
        return SingleResponse.of(result);
    }

    /**
     * 全部收货
     *
     * @param dto
     * @return
     */
    @Path("customerBatchReceipt")
    @POST
    @Operation(summary = "客户收货-待收货-收货-全部收货", tags = CUSTOM_SERVICE, description = "ids必填")
    public SingleResponse<BOList> customerBatchReceipt(@Parameter OrderCustomerGoodsDto dto) {
        log.info("------------------------客户收货-待收货-收货-全部收货 customerReceipt Param：{}------------------------", JSONObject.toJSONString(dto));
        if (CollectionUtils.isEmpty(dto.getIds())) {
            return SingleResponse.buildFailure("-1", "客户订单商品ID集合必填");
        }
        TempOrderReceiptVo tempOrderReceiptVo = orderService.goodsReceiptBatch(dto.getIds());

        //构建结果集
        BOList bolist = new BOList();
        bolist.setData(tempOrderReceiptVo.getOrderGoodsList());
        bolist.setTotal(tempOrderReceiptVo.getOrderGoodsList() == null ? 0 : tempOrderReceiptVo.getOrderGoodsList().size());
        bolist.setSchemaCode(ModelConst.T_ORDER_GOODS_ACCEPT);
        return SingleResponse.of(bolist);
    }

    /**
     * 已完成-导出
     *
     * @param bo
     * @return
     */
    @Path("exportCustomerDone")
    @POST
    @Operation(summary = "客户收货-已完成-导出已完成列表", tags = CUSTOM_SERVICE, description = "入参:{data:{ids:[],fileType:'pdf/xlsx'}}")
    public SingleResponse exportCustomerDone(SaveOrUpdateBO bo) {
        List<String> ids = (List<String>) bo.getData().get("ids");
        if (ObjectUtils.isEmpty(ids)) {
            return SingleResponse.buildFailure("-1", "请求参数ids不能为空");
        }

        String fileType = (String) bo.getData().get("fileType");
        ReportType reportType = ReportType.get(fileType);

        if (reportType == null) {
            return SingleResponse.buildFailure("-1", "请求参数fileType不能为空");
        }

        SingleResponse<BOList> singleResponse = BoQueryUtils.Builder(ModelConst.T_ORDER_CUSTOMER_GOODS)
                .condition()
                .in("id", ids)
                .End().listBO();
        if (!singleResponse.isSuccess()) {
            return singleResponse;
        }
        List<Map<String, Object>> data = singleResponse.getData().getData();

        if (data.isEmpty()) {
            return SingleResponse.buildFailure("-1", "未获取到下载数据");
        }

        String exportField = "{\"id\":\"id\",\"time\":\"createdTime\",\"category\":\"category\",\"brand\":\"brand\",\"name\":\"name\",\"model\":\"model\",\"spec\":\"spec\",\"sku\":\"sku\",\"unit\":\"unit\",\"packageUnit\":\"package_unit\",\"packageNum\":\"package_quantity\",\"delivery\":\"delivery\",\"num\":\"num\",\"taxRate\":\"tax_rate\",\"pretaxPrice\":\"pretax_price\",\"price\":\"price\",\"amount\":\"amount\",\"status\":\"order_vendor_status\",\"memberName\":\"place_order_fullname\",\"orgName\":\"customer_organization_name\",\"customerOrderId\":\"order_customer_id\",\"demandDeptName\":\"demand_department_name\",\"costCenterName\":\"cost_center_name\",\"inquiryMemberName\":\"inquiry_member_name\",\"inquiryId\":\"inquiry_id\",\"erpPO\":\"erp_po\"}";
        JSONObject exportJson = JSON.parseObject(exportField);
        List<Map<String, Object>> fileData = data.stream().map(m -> {
            Map<String, Object> mf = new HashMap<>();
            for (String key : exportJson.keySet()) {

                mf.put(exportJson.getString(key), m.get(key));
            }
            return mf;
        }).collect(Collectors.toList());


        if (log.isDebugEnabled()) {
            log.debug("======================客户订单商品报表导出参数:reportType={},fileData={}", reportType.getId(), JSON.toJSONString(fileData));
        }
        ReportUtils.exportReport("order/order_goods_report_xlsx.jrxml", reportType.getId(), fileData);

        return SingleResponse.buildSuccess();
    }

    @Path("exportCustomerReceived")
    @POST
    @Operation(summary = "客户收货-未完成-导出待收货列表",tags = CUSTOM_SERVICE,description = "入参:{data:{ids:[],fileType:'pdf/xlsx'}}")
    public SingleResponse exportCustomerReceived(SaveOrUpdateBO saveOrUpdateBO){
        List<String> ids = (List<String>) saveOrUpdateBO.getData().get("ids");
        if (ObjectUtils.isEmpty(ids)) {
            return SingleResponse.buildFailure("-1", "请求参数ids不能为空");
        }

        String fileType = (String) saveOrUpdateBO.getData().get("fileType");
        ReportType reportType = ReportType.get(fileType);

        if (reportType == null) {
            return SingleResponse.buildFailure("-1", "请求参数fileType不能为空");
        }


        SingleResponse<BOList> singleResponse = BoQueryUtils.Builder(ModelConst.T_ORDER_CUSTOMER_GOODS)
                .condition()
                .in("id", ids)
                .End().listBO();
        if (!singleResponse.isSuccess()) {
            return singleResponse;
        }
        List<Map<String, Object>> data = singleResponse.getData().getData();

        if (data.isEmpty()) {
            return SingleResponse.buildFailure("-1", "未获取到下载数据");
        }
        String exportField = "{\"id\":\"id\",\"customerOrderId\":\"order_vendor_id\",\"status\":\"order_customer_goods_status\",\"deliverableNum\":\"undelivered_quantity\",\"orgName\":\"vendor_organization_name\",\"brand\":\"brand\",\"name\":\"name\",\"model\":\"model\",\"spec\":\"spec\",\"unit\":\"unit\",\"packageNum\":\"package_quantity\",\"packageUnit\":\"package_unit\",\"taxRate\":\"tax_rate\",\"pretaxTotal\":\"pretax_total\",\"pretaxPrice\":\"pretax_price\",\"price\":\"price\",\"delivery\":\"delivery\",\"freight\":\"freight\",\"receivedNum\":\"quantity_received\",\"customerOrgName\":\"customer_organization_name\",\"total\":\"total\",\"amount\":\"amount\",\"time\":\"createdTime\",\"clientOrderGoodsId\":\"source\",\"num\":\"quantity\",\"deliveredNum\":\"quantity_shipped\"}";
        JSONObject exportJson = JSON.parseObject(exportField);
        List<Map<String, Object>> fileData = data.stream().map(m -> {
            Map<String, Object> mf = new HashMap<>();
            for (String key : exportJson.keySet()) {
                String value = String.valueOf(m.get(exportJson.get(key)));
                if ("status".equals(key)){
                    value= OrderCustomerStatusEnum.valueOf(value).des;
                    mf.put(key, value);
                }else {
                    mf.put(key, m.get(exportJson.getString(key)));
                }

            }
            return mf;
        }).collect(Collectors.toList());


        if (log.isDebugEnabled()) {
            log.debug("======================客户待收货报表导出参数:reportType={},fileData={}", reportType.getId(), JSON.toJSONString(fileData));
        }
        ReportUtils.exportReport("order/order_delivered_goods_report.jrxml", reportType.getId(), fileData);

        return SingleResponse.buildSuccess();


    }

}
